package com.orange.core.security.filter;

import com.orange.core.util.Constants;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class AbstractAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public AbstractAuthenticationFilter(String signInPath, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
        super(new AntPathRequestMatcher(signInPath, HttpMethod.POST.name()));
        setAuthenticationSuccessHandler(successHandler);
        setAuthenticationFailureHandler(failureHandler);
    }

    protected abstract Authentication obtainToken(HttpServletRequest request);

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (HttpMethod.POST.name().equals(request.getMethod()) &&
                (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equalsIgnoreCase(Constants.APPLICATION_JSON_UTF8_VALUE))) {
            return getAuthenticationManager().authenticate(obtainToken(request));
        }
        throw new AuthenticationServiceException("登录认证只支持POST请求");
    }
}
